import 'dart:convert';
import 'dart:typed_data';
import 'package:bnotes/constants.dart';
import 'package:bnotes/helpers/utility.dart';
import 'package:bnotes/pages/app_lock_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:universal_platform/universal_platform.dart';
import 'labels_page.dart';

class SettingsPage extends StatefulWidget {
  @override
  _SettingsPageState createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage> {
  late SharedPreferences sharedPreferences;
  bool isAppLogged = false;
  bool isAppUnlocked = false;
  bool isPinRequired = false;
  late String username;
  late String useremail;
  Uint8List? avatarData;

  bool isAndroid = UniversalPlatform.isAndroid;
  bool isIOS = UniversalPlatform.isIOS;
  bool isWeb = UniversalPlatform.isWeb;
  bool isDesktop = UniversalPlatform.isDesktop;

  getPref() async {
    sharedPreferences = await SharedPreferences.getInstance();
    setState(() {
      isAppUnlocked = sharedPreferences.getBool("is_app_unlocked") ?? false;
      isPinRequired = sharedPreferences.getBool("is_pin_required") ?? false;
      isAppLogged = sharedPreferences.getBool('is_logged') ?? false;
      username = sharedPreferences.getString('nc_userdisplayname') ?? '';
      useremail = sharedPreferences.getString('nc_useremail') ?? '';
      avatarData = base64Decode(sharedPreferences.getString('nc_avatar') ?? '');
    });
  }

  @override
  void initState() {
    super.initState();
    getPref();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        height: MediaQuery.of(context).size.height,
        child: SingleChildScrollView(
          physics:
              BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Padding(
                padding: kGlobalOuterPadding,
                child: Column(
                  children: [
                    Padding(
                      padding: kGlobalCardPadding,
                      child: InkWell(
                        borderRadius: BorderRadius.circular(15.0),
                        onTap: () {
                          Navigator.of(context).push(
                            CupertinoPageRoute(
                              builder: (context) => LabelsPage(
                                noteid: '',
                                notelabel: '',
                              ),
                            ),
                          );
                        },
                        child: ListTile(
                          leading: CircleAvatar(
                            backgroundColor: Colors.purple[100],
                            foregroundColor: Colors.purple,
                            child: Icon(Icons.label_outline),
                          ),
                          title: Text('笔记标签'),
                          subtitle: Text('管理笔记标签'),
                        ),
                      ),
                    ),
                    Padding(
                      padding: kGlobalCardPadding,
                      child: InkWell(
                        borderRadius: BorderRadius.circular(15.0),
                        onTap: () {
                          if (isPinRequired) {
                            showAppLockMenu();
                          } else {
                            callAppLock();
                          }
                        },
                        child: ListTile(
                          leading: CircleAvatar(
                            backgroundColor: Colors.red[100],
                            foregroundColor: Colors.red,
                            child: Icon(Icons.lock_outline),
                          ),
                          title: Text('密码锁'),
                          subtitle: Text('设置您的错题笔记密码锁'),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void showAppLockMenu() {
    showModalBottomSheet(
        context: context,
        backgroundColor: Colors.transparent,
        isDismissible: true,
        builder: (context) {
          return Container(
            child: Padding(
              padding: kGlobalOuterPadding,
              child: Container(
                height: 140,
                child: Card(
                  child: Padding(
                    padding: kGlobalOuterPadding,
                    child: ListView(
                      physics: NeverScrollableScrollPhysics(),
                      children: [
                        InkWell(
                          borderRadius: BorderRadius.circular(15),
                          onTap: () {
                            callAppLock();
                          },
                          child: ListTile(
                            title: Text('重置密码'),
                          ),
                        ),
                        InkWell(
                          borderRadius: BorderRadius.circular(15),
                          onTap: () {
                            unSetAppLock();
                            Navigator.pop(context);
                          },
                          child: ListTile(
                            title: Text('移除密码锁'),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          );
        });
  }

  void callAppLock() async {
    final res = await Navigator.of(context).push(CupertinoPageRoute(
        builder: (context) => AppLockPage(
              appLockState: AppLockState.SET,
            )));
    if (res == true) getPref();
  }

  void unSetAppLock() async {
    setState(() {
      sharedPreferences.setBool("is_pin_required", false);
      sharedPreferences.setBool("is_app_unlocked", true);
      sharedPreferences.setString("app_pin", '');
      isAppUnlocked = true;
      isPinRequired = false;
    });
  }
}
